package com.example.gokuplayalong.service.privateclient.interceptor;


import com.example.gokuplayalong.bases.base.ExceptionHandler;
import com.example.gokuplayalong.bases.mysql.MysqlDruid;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Objects;

public class PrivateHandlerInterceptor {
    static PrivateHandlerInterceptor INSTANCE = null;

    public static PrivateHandlerInterceptor getInstance() {
        if (INSTANCE == null) INSTANCE = new PrivateHandlerInterceptor();
        return INSTANCE;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        try {
            Connection conn = MysqlDruid.dataSource.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("select * from admininfo");
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                if (Objects.equals(rs.getString("token"), request.getHeader("Token"))) {
                    return true;
                }
            }
            conn.close();
        } catch (Throwable e) {
            ExceptionHandler.saveException(Thread.currentThread().getStackTrace()[1].getClassName() + Thread.currentThread().getStackTrace()[1].getMethodName() + Thread.currentThread().getStackTrace()[1].getLineNumber(), e);
        }
        return false;
    }
}
